package com.woniuxy.oldmanapi.utils;

import com.woniuxy.oldmanapi.vo.ResponseResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
public class Upload {
    @Value("${uploadPath}")
    private String uploadUrlPath;
    @PostMapping("/upload/upFile")
    public ResponseResult<String> upFile(@RequestParam("conFile") MultipartFile multipartFile, HttpServletRequest request) {
        ResponseResult<String> result = new ResponseResult<>();
        try {
            // 获取服务器根路径
            String realPath = "D:\\imgs";
            // 指定保存文件的路径
            File file = new File(realPath);
            if (!file.exists()) {
                file.mkdirs();
            }
            String fileName = multipartFile.getOriginalFilename();
            String newFileName = UUID.randomUUID().toString().replace("-", "") + fileName.substring(fileName.lastIndexOf("."));
            file = new File(file, newFileName);
            // 上传文件
            multipartFile.transferTo(file);
            result.setCode(200);
            result.setMsg("文件上传成功");
            result.setData(newFileName);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(204);
            result.setMsg("文件上传失败，请稍后再试");
        }
        return result;
    }
    @PostMapping("/upload/uploadImg")
    public ResponseResult<String> uploadImgsrc(@RequestParam("uploadImg") MultipartFile multipartFile) {
        ResponseResult<String> result = new ResponseResult<>();
        try {
            String filename = multipartFile.getOriginalFilename();
            filename= UUID.randomUUID().toString().replace("-", "") + filename.substring(filename.lastIndexOf("."));
            File file=new File(uploadUrlPath,filename);
            multipartFile.transferTo(file);
            result.setData(filename);
            result.setMsg("上传成功");
            result.setCode(200);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(201);
            result.setMsg("上传失败");
        }
        return result;


    }
}
